
/**
 * 腾讯地图
 * https://lbs.qq.com/webApi/javascriptV2/jsGuide/jsOverview
 */
import React, { useState, useEffect, useRef } from "react";

function getAddress(latLng, cb) {
  var geocoder = new qq.maps.Geocoder();
  geocoder.getAddress(latLng);
  geocoder.setComplete(function (res) {
    cb(res);
  });
  geocoder.setError(function (err) {
    cb(err);
  });
}

const Map = ({ value, onChange, addr = "" }) => {
  const mapRef = useRef();
  const [address, setAddress] = useState(addr);

  useEffect(() => {
    init();
  }, [value, address]);

  const init = () => {
    let map = new qq.maps.Map(mapRef.current, {
      center: new qq.maps.LatLng(
        value?.lat || 39.916527,
        value?.lng || 116.397128
      ),
      zoom: 13,
    });
    let marker = null;
    if (value) {
      marker = new qq.maps.Marker({
        position: new qq.maps.LatLng(value?.lat, value?.lng),
        map: map,
      });
      map.zoomTo(16);
    }

    // if (address) {
    //   let infoWin = new qq.maps.InfoWindow({
    //     map: map,
    //   });
    //   infoWin.open();
    //   infoWin.setContent(address);
    //   infoWin.setPosition(map.getCenter());
    //   map.zoomTo(100);
    // }

    //添加监听事件  获取鼠标点击事件
    qq.maps.event.addListener(map, "click", function (event) {
      if (!marker) {
        marker = new qq.maps.Marker({
          position: event.latLng,
          map: map,
        });
        return;
      }
      onChange(event.latLng);
      getAddress(event.latLng, (res) => {
        if (res.detail?.address) {
          onChange(event.latLng, res.detail?.address);
        }
        setAddress(res.detail.address);
      });
      marker.setPosition(event.latLng);
    });
  };

  return <div ref={mapRef} style={{ height: 500 }}></div>;
};

export default Map;
